package ChatSystem.Thread;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.HashSet;
import java.util.LinkedList;

/**
 * 发送消息线程
 * @create 2022.5.29
 * @author Administrator
 *
 */
public class SendNews extends Thread{

	//保存消息
	private LinkedList<String> queue = new LinkedList();
	
	//发送消息
	private DataOutputStream writer;
	
	//客户端Socket
	private HashSet<Socket> socketSet;
	
	public SendNews(LinkedList<String> queue,HashSet<Socket> socketSet){
		this.queue = queue;
		this.socketSet = socketSet;
	}
	
	@Override
	public void run(){
		
		//如果有消息未发
		if(queue.size() > 0){
			//获取队列中的消息
			String message = queue.pollFirst();;
			//给每个客户端发送消息
			for(Socket socket : socketSet){
				try {
					writer = new DataOutputStream(socket.getOutputStream());
					//发送消息
					System.out.println("发送消息");
					writer.writeUTF(message);
					writer.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
		
}
